//
//  XGProgressIconView.swift
//  SinaWeibo
//
//  Created by 小果 on 16/3/4.
//  Copyright © 2016年 小果. All rights reserved.
//

import UIKit

class XGProgressIconView: UIImageView {

    // 进度值(0~1)
    var progress: CGFloat = 0 {
        didSet {
            progressView.progress = progress
        }
    }
    
    private lazy var progressView: XGProgressView = {
        let p = XGProgressView()
        // 添加控件
       self.addSubview(p)
        // 设置大小
       p.frame = self.bounds
        p.backgroundColor = UIColor.clearColor()
        
        return p
        
    }()
    
//    // 在imageView中，drawRect 函数不会被调用
//    override func drawRect(rect: CGRect) {
//        printLog("come  here")
//    }
    
    // 类中类专供，XGProgressIconView使用
    private class XGProgressView: UIView {
        // 进度值(0~1)
        var progress: CGFloat = 0 {
            didSet {
                setNeedsDisplay()
            }
        }
        
        // drawRect一旦被调用，所有的内容都会被重新绘制
        private override func drawRect(rect: CGRect) {
            
            if progress >= 1 {
                return
            }
//          printLog("\(rect)   \(progress)")
            
            // 绘制曲线
            let center = CGPoint(x: rect.width * 0.5, y: rect.height * 0.5)
            let r = min(rect.width, rect.height) * 0.5
            let start = -CGFloat(M_PI_2)
            let end = 2 * CGFloat(M_PI) * progress + start
            
            let path = UIBezierPath(arcCenter: center, radius: r, startAngle: start, endAngle: end, clockwise: true)
            // 增加指向圆心的路径
            path.addLineToPoint(center)
            // 关闭路径会产生一个扇形
            path.closePath()
            
            // 设置属性
//            path.lineWidth = 10
            UIColor(white: 0.0, alpha: 0.5).setFill()
            
            path.fill()
        }
    }

}
